import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import { keysConf } from '@conf/keys.conf';
import { Subject } from 'rxjs';
import { EACaptchaService } from '../../services';
import { initNECaptchaWithFallback } from './dun';
@Component({
  selector: 'app-captcha',
  templateUrl: './captcha.component.html',
  styleUrls: ['./captcha.component.less'],
})
export class CaptchaComponent implements OnInit {
  @Input() phone!: string; // 手机号
  @Input() url!: string; // api地址
  @Output() done = new EventEmitter<any>();
  captchaIns: any;

  initSubject = new Subject<any>();

  constructor(public captchaService: EACaptchaService) {}

  ngOnInit() {}

  init() {
    const _this = this;
    if (this.captchaIns) {
      return this.initSubject;
    }

    initNECaptchaWithFallback(
      {
        element: '#captcha',
        captchaId: keysConf.yidun_capcha_id,
        mode: 'popup',
        width: '320px',
        onClose: () => {
          // 弹出关闭结束后将会触发该函数
        },
        onVerify: (err: any, data: any) => {
          // console.log('🚀 ~ init ~ data', data);
          if (data?.validate) {
            // 验证通过,获取验证码
            _this.captchaDone(data?.validate);
          }
        },
      },
      (instance: any) => {
        // console.log('🚀 ~ initCaptcha ~ instance', instance);
        // 初始化成功后得到验证实例instance，可以调用实例的方法
        _this.captchaIns = instance;
        this.initSubject.next(_this.captchaIns);
      },
      (err: any) => {
        // 初始化失败后触发该函数，err对象描述当前错误信息
      },
    );

    return this.initSubject;
  }
  /* 网易盾验证通过 */
  captchaDone(validate: any) {
    this.captchaService.getCaptchaByDun(this.phone, validate, this.url || undefined).subscribe((res: any) => {
      // console.log('🚀 ~ 验证通过发送验证码=>', res);
      if (res) {
        this.captchaService.msgSrv.success('验证码发送成功！');
        this.done.emit(null);
      } else {
        this.captchaService.msgSrv.warning(res.msg);
      }
    });
  }
  popUp() {
    if (!this.captchaIns) {
      this.init();
    }
    this.captchaIns.refresh();
    this.captchaIns.popUp();
  }
}
